package com.eascs.gaczcontract.controller;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.o2o.backfee.entity.O2OComReceiveFee;
import com.eascs.admin.o2o.internal.util.MoneyUtil;
import com.eascs.admin.o2o.loan.entity.O2oLoanUserEntity;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.crm.common.entity.CustomerShopInfoEntity;
import com.eascs.crm.common.entity.PubDditem;
import com.eascs.crm.common.service.ICustomerInfoService;
import com.eascs.crm.common.vo.CustomerView;
import com.eascs.crm.common.vo.QueryCustomerVO;
import com.eascs.gaczcontract.entity.HrUnit;
import com.eascs.gaczcontract.service.GaczContractService;
import com.eascs.gaczcontract.service.ToBigModeService;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.ViewContext;

@RestController
@RequestMapping("/contractRests")
public class ContractRestContorller extends BaseRestController {

	@Autowired
	private O2oLoanapplyService o2oLoanapplyService;
	@Reference
	ICustomerInfoService iCustomerInfoService;
	@Autowired
	GaczContractService gaczContractService;
	@Autowired
	ToBigModeService toBigModeService;

	/**
	 * 借款合同（国安村镇）
	 * 
	 * @param
	 * @return
	 */
	public void borrewContrat() {
		// 审批详情
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置显示格式
		ViewContext.put("printDate", df.format(new Date()));
	}

	/**
	 * 借款借据（国安村镇）
	 * 
	 * @param
	 * @return
	 */
	public void borrewIous() {
		// 审批详情
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置显示格式
		ViewContext.put("printDate", df.format(new Date()));
	}

	/**
	 * 连带责任担保书（国安村镇）
	 * 
	 * @param
	 * @return
	 */
	public void jointLiabilityGuarantee() {
		// 审批详情
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置显示格式
		ViewContext.put("printDate", df.format(new Date()));
	}

	/**
	 * 连带责任担保书 企业版（国安村镇）
	 * 
	 * @param
	 * @return
	 */
	public void jointLiabilityGuaranteeQYB() {
		// 审批详情
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置显示格式
		ViewContext.put("printDate", df.format(new Date()));
	}

	/**
	 * 委托支付通知书（国安村镇）
	 * 
	 * @param
	 * @return
	 */
	public void adviceNote() {
		// 审批详情
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置显示格式
		ViewContext.put("printDate", df.format(new Date()));
	}

	/**
	 * 合作协议书（国安村镇）
	 * 
	 * @param
	 * @return
	 */
	public void cooperationProtocol() {
		// 审批详情
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置显示格式
		ViewContext.put("printDate", df.format(new Date()));
	}

	/**
	 * 合同（国安村镇）
	 * 
	 * @param
	 * @return
	 */
	/* 合同数据 */
	@RequestMapping(value = "/contract")
	public HtmlRestResult contractPrint(String billCode, String receiveBank, String bankAccount) {
		// 带货信息
		O2oLoanapplyEntity loanapply = o2oLoanapplyService.fingByBillCode(billCode);
		//借款信息
		O2oLoanUserEntity userInfo = o2oLoanapplyService.fingByloanId(loanapply.getLoanId());
		// 保证金、管理费、风险补偿金
		O2OComReceiveFee receiveFee = o2oLoanapplyService.findExpandByBillCode(billCode);

		// 客户信息（客户基本信息、客户扩展信息、客户门店信息、客户资产信息）
		QueryCustomerVO vo = new QueryCustomerVO();
		vo.setCustomer_id(loanapply.getLoanId());
		CustomerView customer = iCustomerInfoService.geCustomerView(vo);
		// 经办平台全称
		HrUnit hrUnit = gaczContractService.findByUnitno(loanapply.getLtd());
		// 复批金额（大写）
		String bankAmountBigWrite = MoneyUtil.toChinese(formatComma2BigDecimal(loanapply.getEaMount()).toString());
		// 复批金额（小写）
		String eaMountM = toEaMountM(loanapply.getEaMount());
		// 收获地址（省）
		PubDditem province = iCustomerInfoService
				.getCustomerRecipientAddress(customer.getExpansionInfo().getRecipientProvince(), "9");
		// 收获地址（市）
		PubDditem city = iCustomerInfoService
				.getCustomerRecipientAddress(customer.getExpansionInfo().getRecipientCity(), "10");
		// 收获地址（区、县）
		PubDditem country = iCustomerInfoService
				.getCustomerRecipientAddress(customer.getExpansionInfo().getRecipientCounty(), "11");
		List<CustomerShopInfoEntity> mainShop = customer.getShopInfoList();
		// 客户主门店地址
		String mainShopAdd = null;
		// 客户主门店名称
		String mainShopName = null;
		for (int i = 0; i < mainShop.size(); i++) {
			CustomerShopInfoEntity shop = new CustomerShopInfoEntity();
			shop = mainShop.get(i);
			// 判断是否是主门店
			if ("MAN".equals(shop.getShoptype())) {
				mainShopAdd = shop.getLicenceAddress();
				mainShopName = shop.getLicenceName();
			}
		}
		// 借款借据 - 借款金额
		String mount = loanapply.getEaMount().toString();
		StringBuilder addstr = new StringBuilder(mount.substring(0, mount.length() - 9));
		if (addstr.length() == 3) {
			addstr.insert(0, "0");
		}
		if (addstr.length() == 2) {
			addstr.insert(0, "00");
		}
		if (addstr.length() == 1) {
			addstr.insert(0, "000");
		}

		ViewContext.put("eaMount", bankAmountBigWrite);
		ViewContext.put("eaMountM", eaMountM);
		ViewContext.put("userInfo", userInfo);
		ViewContext.put("loanapply", loanapply);
		ViewContext.put("receiveFee", receiveFee);
		ViewContext.put("CustomerView", customer);
		ViewContext.put("hrUnit", hrUnit);
		ViewContext.put("province", province);
		ViewContext.put("city", city);
		ViewContext.put("country", country);
		ViewContext.put("mainShopAdd", mainShopAdd);
		ViewContext.put("mainShopName", mainShopName);
		ViewContext.put("addstr", addstr);

		return HtmlRestResult.popHtmlFragment("gaczContract/gacz_contract");
	}

	@RequestMapping(value = "/contractnull")
	public BaseRestResult<String> print() {
		BaseRestResult<String> result = null;
		result = BaseRestResult.warn("开户行全称或银行卡号不能为空");
		return result;
	}

	private BigDecimal formatComma2BigDecimal(Object obj) {
		String val = String.valueOf(obj);
		if (val == null)
			return new BigDecimal("0.00");

		val = val.replaceAll(",", "");
		if (!isNumber(val))
			return new BigDecimal("0.00");

		BigDecimal decimal = new BigDecimal(val);
		decimal = decimal.setScale(2, BigDecimal.ROUND_UP);

		return decimal;
	}

	private boolean isNumber(String value) {
		return isInteger(value) || isDouble(value);
	}

	private boolean isDouble(String value) {
		try {
			Double.parseDouble(value);
			if (value.contains("."))
				return true;
			return false;
		} catch (NumberFormatException e) {
			return false;
		}
	}

	private boolean isInteger(String value) {
		try {
			Integer.parseInt(value);
			return true;
		} catch (NumberFormatException e) {
			return false;
		}
	}

	public String toEaMountM(Object d) {
		DecimalFormat df = new DecimalFormat("#.00");
		return df.format(d);
	}
}
